var fs=require('fs'),stdin=process.stdin,stdout=process.stdout;

var stats=[];
fs.readdir(process.cwd(), function (err, files) {
   console.log('');

    if(!files.length){
        return console.log('No files to show!');
    }

    console.log('Select which file or directory you want to see\n');

    function file(i){
        var name=files[i];
        fs.stat(__dirname+'/'+name, function (err, st) {
            stats[i]=st;
            if(st.isDirectory()){
                console.log(i+'  '+name+'/');
            }else{
                console.log(i+'  '+name);
            }

            i++;
            if(i==files.length){
                read()
            }else{
                file(i);
            }
        });
    }
    file(0);

    function read(){
        console.log('');
        stdout.write('Enter your choice:');
        stdin.resume();
        stdin.setEncoding('utf8');
        stdin.on('data',option);
    }

    function option(data){
        var name=files[Number(data)];
        if(!name){
            stdout.write('目录不存在，重新输入:');
        }else{
            stdin.pause();
            if(stats[Number(data)].isDirectory()){
                fs.readdir(__dirname+'/'+name, function (err, files) {
                    console.log('');
                    console.log('('+files.length+' files)');
                    files.forEach(function (file) {
                        console.log('  -  '+file);
                    });
                    console.log('');
                });
            }else{
                fs.readFile(__dirname+'/'+name,'utf8', function (err, data) {
                    console.log('');
                    console.log(data);
                })
            }
        }
    }

});

